Main site

Sample codes > Using product weights

Using product weights

As with any LLM AI model outputs, always verify the generated code for accuracy before deploying it live.

For the sample prompts here, your might get different responses since AI models have random elements.

AI Prompt:

I'd like a shipping rate calculator that uses the items total weight, the items total cubic weight and items total price as parameters.
The calculator compares the items total weight in kg to the items total cubic weight. The calculator takes the larger of the two and multiply it by 0.2 cents to calculate the total shipping cost.
If the total items price is more than $500, the calculator provides 10% discount from the total shipping cost. The total item price is the sum of each item price.

The dimension and weight of the each item is contained in the item's metafield namespace object called "shipping". Get the first 15 values in the namespace.
The dimensions are given in cm and the weight is given kilograms.
The delivery date is between 5 to 8 days from now.
Use the cubic conversion rate of 250kg per cubic meter. Make sure to convert units correctly, for example, centimeter to meter.
The rates should be in converted to cents.

AI Output:

import { enrichItemDetails } from "./modules.js";

export async function calculateShippingRates(DATA, env) {
  try {
    // Enrich items with additional details
    DATA = await enrichItemDetails(DATA, [{ namespace: "shipping", size: 15 }]);

    // Calculate total weight and cubic weight
    let totalWeight = 0;
    let totalCubicWeight = 0;
    for (const item of DATA.items) {
      const shippingMetafield = item.metafields.shipping;
      if (shippingMetafield) {
        const length = parseFloat(shippingMetafield.length) / 100; // Convert cm to m
        const width = parseFloat(shippingMetafield.width) / 100; // Convert cm to m
        const height = parseFloat(shippingMetafield.height) / 100; // Convert cm to m
        const weight = parseFloat(shippingMetafield.weight);
        totalWeight += weight;
        totalCubicWeight += length * width * height * 250; // Convert kg to m^3 and multiply by 250kg/m^3
      }
    }

    // Calculate shipping cost
    let shippingCost = Math.max(totalWeight, totalCubicWeight) * 0.2;

    // Apply discount if total price is over $500
    const totalPrice = DATA.items.reduce((acc, item) => acc + item.price, 0);
    if (totalPrice > 50000) {
      shippingCost *= 0.9;
    }

    // Convert shipping cost to cents
    shippingCost = Math.ceil(shippingCost * 100);

    // Calculate delivery dates
    const minDeliveryDate = new Date();
    minDeliveryDate.setDate(minDeliveryDate.getDate() + 5);
    const maxDeliveryDate = new Date();
    maxDeliveryDate.setDate(maxDeliveryDate.getDate() + 8);

    // Return shipping rates
    return {
      rates: [
        {
          service_name: "Standard Shipping",
          service_code: "standard",
          total_price: shippingCost.toString(),
          description: "Standard shipping",
          currency: DATA.currency,
          min_delivery_date: minDeliveryDate.toISOString(),
          max_delivery_date: maxDeliveryDate.toISOString(),
        },
      ],
    };
  } catch (error) {
    // Return error rate
    return {
      rates: [
        {
          service_name: "Error",
          service_code: "error",
          total_price: null,
          description: error.message,
          currency: DATA.currency,
          min_delivery_date: "",
          max_delivery_date: "",
        },
      ],
    };
  }
}